package com.wiken.addressservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wiken.addressservice.entity.Address;
import com.wiken.addressservice.mapper.AddressMapper;
import com.wiken.addressservice.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.parser.Token;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    public boolean hasSameUser(Address address, String token){
        Claims claims = TokenUtil.parseToken(token);

        if(claims == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_NULL, "用户token过期");

        String userId = claims.get("userId", String.class);

        if(address.getUserId() == null) throw new DefaultException(Code.ERROR_ADDRESS_USER_NULL, "未指定用户");

        if(!address.getUserId().equals(userId)) throw new DefaultException(Code.ERROR_AUTHORIZATION, "操作异常");

        return true;
    }
    @Override
    public Page<Address> getAddressAll(Page page, Address address, String token) {
//        hasSameUser(address, token);

        String userId = TokenUtil.getUserIdByToken(token);
        QueryWrapper query = new QueryWrapper<Address>().eq("user_id", userId);

        Page<Address> addressPage = baseMapper.selectPage(page, query);
        return addressPage;
    }

    @Override
    public boolean addAddress(Address address, String token) {
//        hasSameUser(address, token);
        String userId = TokenUtil.getUserIdByToken(token);
        address.setUserId(userId);
        int success = baseMapper.insert(address);
        return success > 0;
    }

    @Override
    public boolean updateAddress(Address address, String token) {
        hasSameUser(address, token);

        int success = baseMapper.updateById(address);

        return success > 0;
    }

    @Override
    public boolean delAddress(Address address, String token) {
        hasSameUser(address, token);

        int success = baseMapper.deleteById(address);

        return success > 0;
    }
}
